package com.haixiaoke.admin;

import com.haixiaoke.saas.common.constant.Constants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.domain.entity.SysMenu;
import com.haixiaoke.saas.common.core.domain.entity.SysUser;
import com.haixiaoke.saas.department.domain.Tenant;
import com.haixiaoke.saas.department.service.ITenantService;
import com.haixiaoke.saas.system.BaseController;
import com.haixiaoke.saas.system.domain.LoginBody;
import com.haixiaoke.saas.system.framework.security.util.SecurityUtils;
import com.haixiaoke.saas.system.framework.web.service.SysLoginService;
import com.haixiaoke.saas.system.framework.web.service.SysPermissionService;
import com.haixiaoke.saas.system.service.ISysMenuService;
import com.haixiaoke.saas.user.domain.BizUserBusiness;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;


@RestController
@RequestMapping("/admin/mobile")
public class MobileLoginController extends BaseController {

    @Autowired
    private SysLoginService loginService;


    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ITenantService tenantService;

    /**
     * 账号密码登录
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    /**
     * 获取用户所属企业列表
     */
    @GetMapping("/company-list")
    public AjaxResult companyList() {
        // 获取用户信息
        BizUserBusiness user = SecurityUtils.getLoginUser().getBizUser();
        Long userId = user.getUserId();
        List<Tenant> tenantList = tenantService.selectDepByUserId(userId);
        return AjaxResult.success(tenantList);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        BizUserBusiness user = SecurityUtils.getLoginUser().getBizUser();
        Set<String> permissions = permissionService.getMenuPermission(user, SecurityUtils.getLoginUser().getTenantId());
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user.getUserId(), SecurityUtils.getLoginUser().getTenantId());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        // 权限集合
        ajax.put("permissions", permissions);
        return ajax;
    }


}